import { Injectable } from '@nestjs/common';
import { MongodbService } from '~/shared/mongodb/mongodb.service';
import { paginate, Pagination, paginateAggregate } from '~/helper/paginate';
import { FilterQuery, isValidObjectId } from 'mongoose';
import { BusinessException } from '../../../common/exceptions/business.exception';
import { ErrorEnum } from '../../../constants/error-code.constant';
import {
  CreateCategoryDto,
  UpdateCategoryDto,
  SortCategoryDto,
  QueryCategoryDto,
} from './category.dto';
import { Category } from '~/shared/mongodb/schema/category.schema';

@Injectable()
export class CategoryService {
  constructor(private readonly mongodbService: MongodbService) {}
  /**
   * 创建新分类
   */
  async create(createProductCategoryDto: CreateCategoryDto) {
    //判断当前分类名称有没有
    const isExist = await this.mongodbService.CategoryModel.exists({
      classifyname: createProductCategoryDto.classifyname,
    });
    if (isExist) {
      throw new BusinessException(ErrorEnum.CATEGORY_IS_EXIST);
    }
    const createdCategory = new this.mongodbService.CategoryModel(
      createProductCategoryDto,
    );
    return createdCategory.save();
  }

  /**
   * 查询所有分类，按排序值升序排列
   */
  async findAll(dto: QueryCategoryDto): Promise<Pagination<Category>> {
    // 1. 构建查询条件
    const query: FilterQuery<Category> = {};

    // 分类名称模糊查询（不区分大小写）
    if (dto.classifyname) {
      query.classifyname = { $regex: dto.classifyname, $options: 'i' };
    }

    // 按是否展示筛选（精确匹配）
    if (dto.isShow !== undefined) {
      query.isShow = dto.isShow;
    }

    console.log(11111, query);

    // 2. 执行分页查询（按 sort 字段升序排列）
    return paginate(
      this.mongodbService.CategoryModel,
      { page: dto.page, pageSize: dto.pageSize }, // 分页参数（来自前端）
      query, // 筛选条件
      { sort: { sort: 1 }, projection: { __v: 0 } }, // 额外配置：排序规则
    );
  }

  /**
   * 查询单个分类
   */
  async findOne(id: string) {
    const category = await this.mongodbService.CategoryModel.findById(
      id,
    ).exec();
    if (!category) {
      throw new BusinessException(ErrorEnum.CATEGORY_NOT_EXIST);
    }
    return category;
  }

  /**
   * 更新分类
   */
  async update(id: string, updateProductCategoryDto: UpdateCategoryDto) {
    const updatedCategory =
      await this.mongodbService.CategoryModel.findByIdAndUpdate(
        id,
        updateProductCategoryDto,
        { new: true },
      ).exec();

    if (!updatedCategory) {
      throw new BusinessException(ErrorEnum.CATEGORY_NOT_EXIST);
    }

    return updatedCategory;
  }

  /**
   * 删除分类
   */
  async remove(id: string): Promise<void> {
    const result = await this.mongodbService.CategoryModel.deleteOne({
      _id: id,
    }).exec();
    if (result.deletedCount === 0) {
      throw new BusinessException(ErrorEnum.CATEGORY_NOT_EXIST);
    }
  }

  /**
   * 批量更新分类排序
   */
  async sortCategories(
    sortDto: SortCategoryDto,
  ): Promise<{ success: boolean }> {
    // 验证排序数据不为空
    if (!sortDto.items?.length) {
      throw new BusinessException(ErrorEnum.EMPTY_SORT_LIST);
    }

    // 循环更新排序值
    for (const item of sortDto.items) {
      // 验证分类ID格式
      if (!isValidObjectId(item.id)) {
        throw new BusinessException(ErrorEnum.INVALID_ID_FORMAT);
      }

      // 验证排序值为有效数字
      const newSortValue = Number(item.newSort);
      if (isNaN(newSortValue)) {
        throw new BusinessException(ErrorEnum.INVALID_SORT_VALUE);
      }

      // 执行更新并检查结果
      const updatedCategory =
        await this.mongodbService.CategoryModel.findByIdAndUpdate(
          item.id,
          { sort: newSortValue },
          { new: true, runValidators: true },
        ).exec();

      // 若更新失败（分类不存在），直接抛出异常
      if (!updatedCategory) {
        throw new BusinessException(ErrorEnum.CATEGORY_NOT_EXIST);
      }
    }

    // 全部更新完成
    return { success: true };
  }
}
